﻿function Account() {
    var me = this;
    //指示是否登录完成停留在本页面
    this.stayPage = false;
    this.loginCompleted = null;
    this.isLogin = false;
    this.vcodeIsShow = false;
    this.init = function () {
        //me.autoLogin();
        //me.validateLoginForm();
        // me.submitLogin();
        me.keyDownOrClick();
        me.displayVcode();
        return me;
    };
    this.isEmail = function (value) {
        // From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
        // Retrieved 2015-06-04
        // If you have a problem with this implementation, report a bug against the above spec
        // Or use custom methods to implement your own email validation
        var result = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value);
        return result;
    };


    //自动登录
    this.autoLogin = function () {

        var result = false;

        var chkRemmberMe = $("#chkRemmberMeIndex").attr("checked") == "checked" ? true : false;
        if (chkRemmberMe) {
            $.ajax({
                type: "POST",
                url: "/Account/Account/AutoLogin",
                data: {
                    t: new Date()
                },
                success: function (data) {

                    if (data.Result) {
                        window.location.href = "/portalindex";
                        me.isLogin = true;
                        result = true;
                    }
                }
            });
        }
        return result;

    }
    ///验证手机号码
    this.isMobile = function (value) {
        var result = /^1[3587]\d{9}$/.test(value);
        return result;
    };

    //验证Address表单
    //this.validateLoginForm = function () {
    //    $('#frmLogin').validate({
    //        onfocusout: false,
    //        ignore: ".ignore",
    //        rules: {
    //            txtAccount: { required: true, rangelength: [3, 40] },
    //            txtPassword: { required: true, rangelength: [6, 16] }
    //        },
    //        messages: {
    //            txtAccount: {
    //                required: "手机号码/邮箱",
    //                rangelength: "长度请控制在3-40 个字符"
    //            },
    //            //txtValidCode: {
    //            //    required: "请输入验证码！",
    //            //    rangelength: jQuery.validator.format("长度请控制在{0}位")
    //            //},
    //            txtPassword: {
    //                required: "请输入6-16位密码",
    //                rangelength: "密码长度请控制在6-16 个字符"
    //            }
    //        },
    //        errorPlacement: function (error, element) {

    //            //第一个参数是错误的提示文字，第二个参数是当前输入框
    //            //设置提示样式，在这里设置
    //            element[0].placeholder = error[0].innerHTML;
    //            $(element[0]).parent().css('border', '1px solid #f74b1f');
    //            // error.appendTo(element.siblings("span"));
    //            var parment = element.parent();//.append();
    //        },
    //        success: function (obj) {
    //        },

    //        invalidHandler: function (event, validator) {
    //            //统计错误个数
    //            var errors = validator.numberOfInvalids();
    //        }
    //    });
    //};


    this.submitLogout = function () {
        $.ajax({
            type: "POST",
            url: "/Account/Account/Logout",
            data: {
            },
            success: function (data) {
                alert(data);
            }
        });
    };

    //隐藏/显示 验证码 输入框
    this.displayVcode = function (loginFailedCounter, index) {
        if (loginFailedCounter > 2) {
            me.vcodeIsShow = true;
            if (index == undefined || index == null) {
                $("#VCodeBox").slideDown();

                if ($("#img_VCode").length > 0) { $("#img_VCode").attr('src', '/Common/GetVCode?t=' + (new Date().getTime())); } //防止反复请求验证码
            } else {
                $("#VCodeBox" + index).slideDown();

                if ($("#img_VCode" + index).length > 0) { $("#img_VCode" + index).attr('src', '/Common/GetVCode?t=' + (new Date().getTime())); } //防止反复请求验证码
            }

            if (window['changePosition'] != undefined) {
                window['changePosition']($("#btnSubmitLogin"));
            }
        } else {
            me.vcodeIsShow = false;
        }
    };

    $("#txtAccount,#txtPassword,#VCode").focus(function () {
        $(this).parent().css('border', '1px solid #a1a4ad');
        // $("#txtPassword").parent().css('border', '1px solid #a1a4ad');
    });
    $("#txtAccount,#txtPassword,#VCode").blur(function () {
        //$(this).parent().css('border', '1px solid #a1a4ad');
        $(this).parent().css('border', '1px solid #e1e2e6');
    });
    this.keyDownOrClick = function () {
        $("#txtAccount,#txtPassword,#VCode").keydown(function (key) {
            //Enter key press
            if (key.which == 13) {
                me.submitLogin();
            }
        });
        $("#btnSubmitLogin").click(function () {
            me.submitLogin();
        });

        $("#txtAccountIndex,#txtPasswordIndex,#VCodeIndex").keydown(function (key) {
            //Enter key press
            if (key.which == 13) {
                me.submitLogin("Index");
            }
        });
        $("#btnSubmitLoginIndex").click(function () {
            me.submitLogin("Index");
        });
    };
    this.submitLogin = function (index) {
        if (index == undefined || index == null) index = "";

        var vCode = $("#VCode" + index).val();
        var account = $("#txtAccount" + index).val();
        var password = $("#txtPassword" + index).val();
        if (account === '' || account === undefined) {
            $("#txtAccount" + index).attr('placeholder', '请输入用户名');
            $("#txtAccount" + index).parent().css('border', '1px solid #f74b1f');
            return;
        }

        ///验证手机号码
        var isMobile = function(value) {
            var result = /^1[3587]\d{9}$/.test(value);
            return result;
        };

        var isEmail = function (value) {
            var result = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value);
            return result;
        };

        if (isNaN(account) && !isEmail(account)) {
            $("#txtAccount" + index).val('').attr('placeholder', '请输入正确的手机号/邮箱');
            $("#txtAccount" + index).parent().css('border', '1px solid #f74b1f');
            return;
        }

        if (!isNaN(account) && !isMobile(account)) {
            $("#txtAccount" + index).val('').attr('placeholder', '请输入正确的手机号/邮箱');
            $("#txtAccount" + index).parent().css('border', '1px solid #f74b1f');
            return;
        }

        if (password === '' || password === undefined) {
            $("#txtPassword" + index).attr('placeholder', '请输入密码');
            $("#txtPassword" + index).parent().css('border', '1px solid #f74b1f');
            return;
        }
        if (me.vcodeIsShow === true) {
            if (vCode === '' || vCode === undefined) {
                $("#VCode" + index).val('');
                $("#VCode" + index).attr("placeholder", '请输入验证码');
                $("#VCode" + index).parent().css('border', '1px solid #f74b1f');
                return;
            }
        }
        var chkRemmberMe = $("#chkRemmberMe" + index).attr("checked") == "checked" ? true : false;
        var vCode = $("#VCode" + index).val();

        var loginUrl = "/Account/Account/Login";

        $.ajax({
            type: "POST",
            url: loginUrl,
            data: {
                Account: account,
                Password: password,
                RemmberMe: chkRemmberMe,
                VCode: vCode
            },
            success: function (result) {
                if (result.LoginResult.Result) {
                    //神策调用
                    try {
                        var resuluserid = result.LoginResult.Content;
                        if (resuluserid !== null && resuluserid !== '') {
                            window.FMAnalytics && window.FMAnalytics.login(USERID);
                        }
                    }
                    catch (e) {
                        console.error(e.message);
                    }

                    if (!me.stayPage) {
                        window.location.href = "/portalindex";
                    }
                    else {
                        me.loginCompleted(result);
                    }
                }
                else {
                    if (result.LoginResult.ResultCode == 101) {
                        $("#txtAccount" + index).val('');
                        $("#txtAccount" + index).attr("placeholder", result.LoginResult.Content);
                        $("#txtAccount" + index).parent().css('border', '1px solid #f74b1f');
                        $("#VCode" + index).parent().css('border', '1px solid #e1e2e6');
                    }
                    else if (result.LoginResult.ResultCode == 102) {

                        $("#txtPassword" + index).val('');
                        $("#txtPassword" + index).attr("placeholder", result.LoginResult.Content);
                        $("#txtPassword" + index).parent().css('border', '1px solid #f74b1f');
                        $("#VCode" + index).parent().css('border', '1px solid #e1e2e6');
                    }
                    else if (result.LoginResult.ResultCode == 103) {
                        $("#txtAccount" + index).parent().css('border', '1px solid #e1e2e6');
                        $("#txtPassword" + index).parent().css('border', '1px solid #e1e2e6');
                        $("#VCode" + index).parent().css('border', '1px solid #f74b1f');
                        $("#VCode" + index).val('');
                        $("#VCode" + index).attr("placeholder", result.LoginResult.Content);
                    }
                    else if (result.LoginResult.ResultCode == 104) {
                        $("#txtPassword" + index).val('');
                        $("#txtPassword" + index).attr("placeholder", result.LoginResult.Content);
                        confirmBox("用户未激活,是否重新发送激活邮件", ReSend, $("#txtAccount" + index).val());
                    }
                    else if (result.LoginResult.ResultCode == 106) {
                        $("#txtPassword" + index).val('');
                        $("#txtPassword" + index).attr("placeholder", result.LoginResult.Content);
                        msg("帐号已禁用，请联系客服", 3);
                    }
                    //$("#img_VCode").attr('src', '/Common/GetVCode?t='+(new Date().getTime()));
                    me.displayVcode(result.LoginFailedCounter, index);
                }
            }
        });
    };

    return me;
}

function ReSend(email) {
    $.ajax({
        type: "POST",
        url: "/Account/MT4Register/ReSend",
        data: {
            Email: email
        },
        success: function (result) {
            if (result.ResultCode == 1) {
                msg("激活邮件已经重新发送到您的邮箱，请查收");
                newWin("http://mail." + email.split('@')[1]);
            }
            else {
                msg("邮件激活码发送失败",1);
            }
        }
    });
}

function newWin(url) {
    var a = $("<a href='" + url + "' target='_blank'></a>").get(0);
    var e = document.createEvent('MouseEvents');
    e.initEvent('click', true, true);
    a.dispatchEvent(e);
}
